<template>
    <vxe-grid
        ref='xGrid'
        :class="refresh?'refresh-table':null"
        @form-reset="btnFormReset"
        @toolbar-tool-click="toolbarToolClickEvent"
        @current-change="currentChange"
        @toolbar-button-click="toolbarButtonClickEvent"
        v-bind="gridOptions">
        <!-- 操作栏 -->
      <template #toolbar_buttons>
        <slot name="toolbar_buttons">
        </slot>
      </template>  
        <!-- 状态栏 -->
      <template #status-switch="{row,column}">
              <el-switch v-if="switchType"
              v-model="row[column.property]"
              class="switchStyle"      
              style="--el-switch-on-color: #04ae70;" 
              active-text="启用" 
              inactive-text="禁用" 
              @change="onChange(row)"/> 
              <el-switch v-else
              class="switchStyle" 
              v-model="row[column.property]"
              active-color="#dcdfe6"
              inactive-color="#04ae70"
              active-text="禁用" 
              inactive-text="启用" 
              @change="onChange(row)"/>
      </template>  

        <template #addButtom>
          <auth-tag :code="addCode">
            <div class="xtable-form-btn">
              <el-button
                size="small"
                type="primary"
                class="btn-add create-icon"
                @click="btnAdd()"
              >
                <img src="@/assets/dataStation/icon-create.png">
                {{addText}}</el-button>
            </div>
          </auth-tag>
      </template>
      <!-- 年度 -->
    <template #dateRange="{ data,property }">
      <el-date-picker
          v-model="data[property]"
          style="width:100%"
          class="plan-daterange"
          value-format="YYYY-MM-DD 00:00:00"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
    </template>
      <!-- 操作栏 -->
      <template #actions="{ row, rowIndex }">
        <slot name="actions" :row="row" :rowIndex="rowIndex"> </slot>
      </template>    
      <template #cells="{ row, rowIndex }">
           <slot name="cells" :row="row" :rowIndex="rowIndex"> </slot>
      </template>   
       <template #cells1="{ row, rowIndex }">
           <slot name="cells1" :row="row" :rowIndex="rowIndex"></slot>
      </template> 
    </vxe-grid>
  </template>
  
  <script setup>
  import { computed,ref} from 'vue'
  import {getListDataPage} from '@/api/queryVxegrid'
  const xGrid = ref(null)
  const refresh = ref(false)
  const props = defineProps({
    tableHeight: {
        type:  String,
        default: 'auto'
      },
      toolbarConfig: {
        type: Boolean,
        default: true
      },
      refresh: { //刷新
        type: Boolean,
        default: true
      },
      import: { //导入
        type: Boolean,
        default: false
      },
      export: { //导出
        type: Boolean,
        default: false
      },
      print: { //打印
        type: Boolean,
        default: false
      },
      zoom: { //全屏
        type: Boolean,
        default: true
      },
      custom: { //选择列展示
        type: Boolean,
        default: true
      },
      columnsList: { //列表数据
        type: Array,
        default() {
          return []
        }
      },
      toolButtons: { //工具栏
        type: Array,
        default() {
          return []
        }
      },
      formConfig: { //查询表单
        type: [Object, Boolean],
        default() {
          return {}
        }
      },
      apiUrl: { //接口地址
        type: String,
        default() {
          return null
        }
      },
      method: {  //请求方式
        type: String,
        default() {
          return 'get'
        }
      },
      pageSize: { //分页默认行数
        type: Number,
        default: 10
      },
      pagerConfig: {
        type: Boolean,
        default() {
          return true
        }
      },
      queryData:{
        type:Object,
        default(){
            return {}
        }
      },
      addText:{
        type:String,
        default:'创建方案'
      },
      addCode:{
        type:String,
        default:''
      },
      switchType:{
        type:Boolean,
        default:true
      },
      showOverflow:{
        type:Boolean,
        default:true
      },
      spanList:{
        type: Array,
        default() {
          return []
        }
      },
      rowClassName:{
        type:Function,
        default(){
          return {}
        }
      },
      recombinationData:{
        type:Boolean,
        default:false
      }
  })
  const emit = defineEmits(
    ['saveClick',
    'toolbarButtonClickEvent',
    'toolbarToolClickEvent',
    'currentChange',
    'switchChange',
    'changeIndex'])

 const gridOptions = computed(()=>{
    {
        return {
          border: true,
          resizable: true,
          showHeaderOverflow: true,
          showOverflow: props.showOverflow,
          height: props.tableHeight,
          highlightHoverRow: true,
          highlightCurrentRow: true,
          keepSource: true,
          id: 'gridId',
          rowId: 'id',
          sortConfig: {
            trigger: 'cell',
            remote: true
          },
          filterConfig: {
            remote: true
          },
          pagerConfig: {
            pageSize: props.pageSize,
            enabled: props.pagerConfig,
            pageSizes: [10, 15, 20, 50],
            layouts:['Total','PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump']
          },
          formConfig: props.formConfig,
          toolbarConfig: props.toolbarConfig ? {
            slots: {buttons: 'toolbar_buttons'},
            visibel: false,
            buttons: props.toolButtons,
            refresh: props.refresh,//刷新 
            import: props.import,//导入
            export: props.export,//导出
            print: props.print, //打印
            zoom: props.zoom, //全屏
            custom: props.custom //选择列展示
          } : false,
          proxyConfig: {
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
              result: 'result', // 配置响应结果列表字段
              total: 'page.total' // 配置响应结果总页数字段
            },
            // 只接收Promise，不关心系实现方式
            ajax: {
              // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
              query: ({page, sorts, filters, form}) => {
                return new Promise((resolve, reject) => {
                  if (!props.apiUrl) {
                    return
                  }
                  getListDataPage({
                        url: props.apiUrl,
                        method: props.method
                      },
                      {
                        page: page.currentPage,
                        limit: page.pageSize,
                        ...form,
                        ...props.queryData
                      }).then((res) => {
                    if (res && props.pagerConfig) { //分页
                      let data = res.data || res.rows ||[]
                      //采购订单列表数据重组
                      if(props.recombinationData){
                        let newList =[]
                        data = data.forEach(list => {
                          list.omsOrderItemVoList.forEach((item)=>{
                            newList.push({...item,...list})
                          })
                        })
                        resolve({
                        result: newList,
                        page: {
                          total: res.total,
                          pageNum: page.currentPage,
                          pageSize: page.pageSize
                        }
                      })
                      }else{
                        resolve({
                        result: data,
                        page: {
                          total: res.total,
                          pageNum: page.currentPage,
                          pageSize: page.pageSize
                        }
                      })
                      }
      
                    } else {
                      resolve(res.data || res.rows)
                    }
                  })
                })
              }
            }
          },
          columns: props.columnsList,
          columnConfig:{useKey:'Id'},
          rowConfig:{useKey:'Id'},
          checkboxConfig: {
            // labelField: 'id',
            reserve: true,
            highlight: true,
            range: true
          },
          spanMethod ({ row, _rowIndex, column, visibleData }){
						const fields = props.spanList
						function getValueByData(obj,path) {
							let paths = path.split('.');
							let res = obj;
							let prop;
							while(prop = paths.shift()) {
								if(res[prop]){
                   res = res[prop]
								}
							}
							return res;
						}
						if(column.property){
							const cellValue =getValueByData(row,column.property)
							if (cellValue && fields.includes(column.property)) {
								const prevRow = visibleData[_rowIndex - 1]
								let nextRow = visibleData[_rowIndex + 1]
									if (prevRow && getValueByData(prevRow,column.property) === cellValue) {
										return { rowspan: 0, colspan: 0 }
										} else {
										let countRowspan = 1
										while (nextRow && getValueByData(nextRow,column.property)=== cellValue) {
											nextRow = visibleData[++countRowspan + _rowIndex]
										}
										if (countRowspan > 1) {
											return { rowspan: countRowspan, colspan: 1 }
										}
									}
							}
						}
					},
          rowClassName:props.rowClassName
        }
      }
 })

 let cleanRefresh =null
    const btnFormReset =()=>{
      refresh.value = true
      if(cleanRefresh){
       clearTimeout(cleanRefresh)
      }
       cleanRefresh=  setTimeout(() => {
        refresh.value = false
      }, 1000);
    }
      //table工具栏事件
   const toolbarButtonClickEvent=({code})=> {
    emit('toolbarButtonClickEvent', code)
    }
      //from工具栏事件
      const  toolbarToolClickEvent=({code})=> {
        emit('toolbarToolClickEvent', code)
      }
      const currentChange=(data)=> {
        emit("currentChange", data.row);
        emit("changeIndex", data.rowIndex);
      }
    const loadData=()=>{ //更新列表
      xGrid.value.commitProxy('query')
    }
    const btnAdd=()=>{ //更新列表
      emit('saveClick', {})
    }
    const onChange=(row)=>{ //更新列表
      emit('switchChange', row)
    }
    const getTableData=()=>{ //获取表格数据
     return  xGrid.value.getTableData().tableData
    }
    defineExpose({loadData,getTableData})

  </script>
  